import {Button, ScrollView, Text, View} from '@tarojs/components'
import Taro, {useDidShow} from '@tarojs/taro'
import type React from 'react'
import {useCallback, useState} from 'react'
import {getCurrentUser, type User} from '@/api'
import {getUserInfo, isLoggedIn, logout} from '@/utils/auth'

const Profile: React.FC = () => {
  const [user, setUser] = useState<User | null>(null)
  const [loading, setLoading] = useState(true)

  const loadData = useCallback(async () => {
    if (!isLoggedIn()) {
      setLoading(false)
      return
    }

    // 先从本地存储获取用户信息
    const localUser = getUserInfo()
    if (localUser) {
      setUser(localUser)
    }

    // 然后从服务器获取最新信息
    try {
      const result = await getCurrentUser()
      if (result.success && result.data) {
        setUser(result.data)
      }
    } catch (error) {
      console.error('获取用户信息失败:', error)
    } finally {
      setLoading(false)
    }
  }, [])

  useDidShow(() => {
    loadData()
  })

  const handleLogin = () => {
    Taro.navigateTo({url: '/pages/login/index'})
  }

  const handleLogout = () => {
    Taro.showModal({
      title: '提示',
      content: '确定要退出登录吗？',
      success: (res) => {
        if (res.confirm) {
          logout()
          setUser(null)
          Taro.showToast({
            title: '已退出登录',
            icon: 'success'
          })
        }
      }
    })
  }

  const handleMyOrders = () => {
    Taro.switchTab({url: '/pages/orders/index'})
  }

  if (loading) {
    return (
      <View className="min-h-screen flex items-center justify-center bg-gray-50">
        <Text className="text-gray-500">加载中...</Text>
      </View>
    )
  }

  if (!isLoggedIn() || !user) {
    return (
      <View style={{background: 'linear-gradient(to bottom, #EFF6FF, #FFFFFF)', minHeight: '100vh'}}>
        <ScrollView scrollY className="box-border" style={{height: '100vh', background: 'transparent'}}>
          <View className="px-4 py-12">
            <View className="text-center mb-8">
              <View className="w-24 h-24 bg-gray-200 rounded-full mx-auto mb-4 flex items-center justify-center">
                <View className="i-mdi-account text-6xl text-gray-400"></View>
              </View>
              <Text className="text-xl font-bold text-gray-900 block mb-2">未登录</Text>
              <Text className="text-sm text-gray-500 block">登录后可查看个人信息和订单</Text>
            </View>

            <Button
              onClick={handleLogin}
              className="w-full bg-blue-600 text-white py-3 rounded-xl font-bold text-base"
              style={{
                backgroundColor: '#2563eb',
                color: 'white',
                border: 'none'
              }}>
              立即登录
            </Button>
          </View>
        </ScrollView>
      </View>
    )
  }

  return (
    <View style={{background: 'linear-gradient(to bottom, #EFF6FF, #FFFFFF)', minHeight: '100vh'}}>
      <ScrollView scrollY className="box-border" style={{height: '100vh', background: 'transparent'}}>
        <View className="px-4 py-6">
          <View className="bg-white rounded-2xl shadow-sm p-6 mb-4">
            <View className="flex items-center mb-6">
              <View className="w-16 h-16 bg-blue-100 rounded-full flex items-center justify-center mr-4">
                <View className="i-mdi-account text-4xl text-blue-600"></View>
              </View>
              <View className="flex-1">
                <Text className="text-xl font-bold text-gray-900 block mb-1">{user.phone}</Text>
                {user.email && <Text className="text-sm text-gray-500 block">{user.email}</Text>}
              </View>
            </View>

            <View className="grid grid-cols-1 gap-4">
              <View className="bg-blue-50 rounded-xl p-4 text-center">
                <View className="i-mdi-ticket text-3xl text-blue-600 mb-2"></View>
                <Text className="text-sm text-gray-600 block">我的订单</Text>
              </View>
            </View>
          </View>

          <View className="bg-white rounded-2xl shadow-sm mb-4 overflow-hidden">
            <View
              className="flex items-center justify-between p-4 border-b border-gray-100 active:bg-gray-50"
              onClick={handleMyOrders}>
              <View className="flex items-center">
                <View className="i-mdi-clipboard-text text-2xl text-gray-600 mr-3"></View>
                <Text className="text-base text-gray-900">我的订单</Text>
              </View>
              <View className="i-mdi-chevron-right text-xl text-gray-400"></View>
            </View>

            <View
              className="flex items-center justify-between p-4 border-b border-gray-100 active:bg-gray-50"
              onClick={() => Taro.navigateTo({url: '/pages/contacts/index'})}>
              <View className="flex items-center">
                <View className="i-mdi-account-multiple text-2xl text-gray-600 mr-3"></View>
                <Text className="text-base text-gray-900">常用联系人</Text>
              </View>
              <View className="i-mdi-chevron-right text-xl text-gray-400"></View>
            </View>

            <View className="flex items-center justify-between p-4 active:bg-gray-50">
              <View className="flex items-center">
                <View className="i-mdi-cog-outline text-2xl text-gray-600 mr-3"></View>
                <Text className="text-base text-gray-900">设置</Text>
              </View>
              <View className="i-mdi-chevron-right text-xl text-gray-400"></View>
            </View>
          </View>

          <View className="bg-white rounded-2xl shadow-sm mb-4 overflow-hidden">
            <View className="flex items-center justify-between p-4 border-b border-gray-100">
              <View className="flex items-center">
                <View className="i-mdi-help-circle-outline text-2xl text-gray-600 mr-3"></View>
                <Text className="text-base text-gray-900">帮助与反馈</Text>
              </View>
              <View className="i-mdi-chevron-right text-xl text-gray-400"></View>
            </View>

            <View className="flex items-center justify-between p-4">
              <View className="flex items-center">
                <View className="i-mdi-information-outline text-2xl text-gray-600 mr-3"></View>
                <Text className="text-base text-gray-900">关于我们</Text>
              </View>
              <View className="i-mdi-chevron-right text-xl text-gray-400"></View>
            </View>
          </View>

          <Button
            onClick={handleLogout}
            className="w-full bg-white text-red-600 py-3 rounded-xl font-bold text-base border border-red-200"
            style={{
              backgroundColor: 'white',
              color: '#dc2626',
              border: '1px solid #fecaca'
            }}>
            退出登录
          </Button>
        </View>
      </ScrollView>
    </View>
  )
}

export default Profile
